package com.cn.kabalifeuser.ui.order.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.LazyFragment;
import com.cn.kabalifeuser.callback.SchedulerTransformer;
import com.cn.kabalifeuser.config.Constants;
import com.cn.kabalifeuser.config.CustomRefreshListener;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.RefreshHelper;
import com.cn.kabalifeuser.event.RxBus;
import com.cn.kabalifeuser.event.RxBusBean;
import com.cn.kabalifeuser.ui.integral.bean.WxPayBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.order.activity.ServiceOrderDetailsActivity;
import com.cn.kabalifeuser.ui.release.activity.DepositPayActivity;
import com.cn.kabalifeuser.ui.release.activity.ReleaseAddCommentActivity;
import com.cn.kabalifeuser.ui.release.bean.PayResult;
import com.cn.kabalifeuser.ui.release.bean.ReleaseListBean;
import com.cn.kabalifeuser.ui.release.bean.ZfbBean;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.GsonUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.cn.kabalifeuser.view.dialogView.OrderTuiDialog;
import com.cn.kabalifeuser.view.dialogView.PayErrDialog;
import com.cn.kabalifeuser.view.xx.MyRatingBar;
import com.kongzue.dialog.v2.SelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by 晓林 on 2020/9/7.
 * function: 服务订单
 */
public class ServiceOrderFragments extends LazyFragment<ServiceFragmentslView, ServiceFragmentsPresenter> implements ServiceFragmentslView, CommonPopupWindow.ViewInterface {
    @BindView(R.id.rv_notice)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private View notDataView;
    OrderAdapter mAdapter;
    List<ReleaseListBean.ResultBean.DataBean> mList;
    private int mId;


    int paySign = 1;


    int service_id = -1;//返回的订单id
    String service_Money;//金额

    private CommonPopupWindow popupWindowPay, popupWindowCoupon;
    OrderTuiDialog orderTuiDialog;
    public static ServiceOrderFragments getInstance(int mid) {
        ServiceOrderFragments fragment = new ServiceOrderFragments();
        fragment.mId = mid;
        return fragment;
    }

    @Override
    protected ServiceFragmentsPresenter createPresenter() {
        return new ServiceFragmentsPresenter();
    }

    @Override
    protected void onUserVisible() {
        pagehttp = 1;
        getListData();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.recyclerview_refresh;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager3);
        recyclerView.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new OrderAdapter(R.layout.fragment_order_item, mList, mId);
//                mAdapter = new CouponAdapter(R.layout.pw_commodity_coupon_item, mList, mId);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(mAdapter);
        notDataView = getLayoutInflater().inflate(R.layout.show_empty_view, (ViewGroup) recyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", mAdapter.getItem(position).getId());
                $startActivity(ServiceOrderDetailsActivity.class, bundle);
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_btn_colce:
                        SelectDialog.show(getMe(), "提示", "确定要申请退款吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.onRefundDepositData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId());
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        break;
                    case R.id.tv_btn_pay:
                        ReleaseListBean.ResultBean.DataBean bean = mAdapter.getItem(position);
//                        service_id = mAdapter.getItem(position).getId();
//                        service_Money = mAdapter.getItem(position).getBalance();
//                        showPay();
                        Bundle bundle = new Bundle();
                        List<String> mListStr = new ArrayList<>();
                        for (int i = 0; i < bean.getBus_service_type().size(); i++) {
                            mListStr.add(bean.getBus_service_type().get(i).getTitle());
                        }
                        bundle.putInt("sign", 2);
                        bundle.putInt("getService_id", bean.getId());
                        bundle.putInt("getBusiness_id", bean.getBusiness_id());
                        bundle.putString("getBus_title", bean.getTitle());
                        bundle.putString("getBus_cover", bean.getBus_cover());
                        bundle.putString("getBus_fraction", bean.getBus_fraction());
                        bundle.putString("getAddress_info", bean.getAddress_info());
                        bundle.putStringArrayList("mListStr", (ArrayList<String>) mListStr);
                        bundle.putString("getDeposit", bean.getDeposit());
                        $startActivity(DepositPayActivity.class, bundle);

                        break;
                    case R.id.tv_btn_comment:
                        bundle = new Bundle();
                        bundle.putString("s_Original_price", String.valueOf(mAdapter.getItem(position).getTrue_money()));
                        bundle.putString("s_Fraction", mAdapter.getItem(position).getBus_fraction());
                        bundle.putString("s_Created_at", mAdapter.getItem(position).getCreated_at());
                        bundle.putString("s_Title", mAdapter.getItem(position).getBus_title());
                        bundle.putString("s_Good_img", mAdapter.getItem(position).getBus_cover());
                        bundle.putInt("business_id", mAdapter.getItem(position).getBusiness_id());
                        bundle.putInt("service_type", mAdapter.getItem(position).getId());
                        $startActivity(ReleaseAddCommentActivity.class, bundle);
                        break;
                    case R.id.tv_btn_tui:

                        if (orderTuiDialog==null)
                          orderTuiDialog=new OrderTuiDialog(getMe());
                        orderTuiDialog.getTv_btn_next().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!TextUtils.isEmpty(orderTuiDialog.getEt_content().getText().toString().trim()))
                                {
                                    mPresenter.onOrderTuiData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId(), orderTuiDialog.getEt_content().getText().toString().trim());
                                }else RxToast.error("请输入申诉原因");
                            }
                        });

                        orderTuiDialog.show();




                        break;
                }
            }
        });


        initRefreshLayout();

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean.class)
                .compose(new SchedulerTransformer<RxBusBean>())
                .subscribe(new Action1<RxBusBean>() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void call(RxBusBean rxBusBean) {
                        if (rxBusBean.getId() == 2004 && rxBusBean.getSign() == 2004) {
                            RxToast.success("支付成功");
                            Constants.PAY_SIGN = 0;
                            refreshLayout.autoRefresh();
                        }
                    }
                });

    }

    /**
     * 支付
     */
    private void showPay() {
        if (popupWindowPay != null && popupWindowPay.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_commodity_pay, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowPay = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_commodity_pay)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .setOutsideTouchable(false)
                .create();
        popupWindowPay.showAtLocation(getActivity().findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }


    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            //todo 支付
            case R.layout.pw_commodity_pay:
                ImageView img_check_weixin = view.findViewById(R.id.img_check_weixin);
                ImageView img_check_zfb = view.findViewById(R.id.img_check_zfb);
                img_check_weixin.setImageResource(R.drawable.check_true);
                img_check_zfb.setImageResource(R.drawable.check_false);
                paySign = 1;

                view.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Constants.PAY_SIGN = 0;
                        if (popupWindowPay != null)
                            popupWindowPay.dismiss();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_zfb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_false);
                        img_check_zfb.setImageResource(R.drawable.check_true);
                        paySign = 2;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_weixin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_true);
                        img_check_zfb.setImageResource(R.drawable.check_false);
                        paySign = 1;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_qianbao).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_yinlian).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.tv_btn_pay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //todo 调用支付接口
                        mPresenter.onPayGoData(LoginHelper.getLonginData().getResult(), service_id, service_Money, paySign);
                    }
                });
                break;
        }
    }

    /**
     * 刷新
     */
    public void initRefreshLayout() {
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {
                pagehttp++;
                if (null != mList) {
                    getListData();
                }
            }
        });
    }

    private void getListData() {
        mPresenter.onOrderListData(LoginHelper.getLonginData().getResult(), (mId + 2), pagehttp, pageNum);
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        RxToast.error(msg);

    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onOrderListSuccess(ReleaseListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        if (pagehttp == 1) {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
            } else {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }

        }
    }

    @Override
    public void onRefundDepositSuccess(MsgBean bean) {
        //申请退款。
        RxToast.success(bean.getMsg());
        refreshLayout.autoRefresh();
    }

    @Override
    public void onPaySuccess(String json) {
        if (paySign == 2) {
            //todo 支付宝
            ZfbBean bean = GsonUtil.GsonToJsonClass(json, ZfbBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                //TODO 支付宝支付
                final String orderInfo = bean.getResult();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(
                                getActivity());
                        Map<String, String> result = alipay
                                .payV2(orderInfo, true);
                        LoggerUtils.d("支付宝数据:" + result.toString());
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());
        } else if (paySign == 1) {
            //todo 微信
            WxPayBean bean = GsonUtil.GsonToJsonClass(json, WxPayBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                Constants.PAY_SIGN = 2004;
                IWXAPI api = WXAPIFactory.createWXAPI(getMe(), bean.getResult().getAppid());
                api.registerApp(bean.getResult().getAppid());
                PayReq req = new PayReq();
                req.appId = bean.getResult().getAppid();
                req.partnerId = bean.getResult().getPartnerid();  //商户id
                req.prepayId = bean.getResult().getPrepayid(); //预支付交易会话ID
                req.packageValue = bean.getResult().getPackageX(); //扩展字段
                req.nonceStr = bean.getResult().getNoncestr(); //随机字符串
                req.timeStamp = String.valueOf(bean.getResult().getTimestamp());//时间戳
                req.sign = bean.getResult().getSign(); //签名
                api.sendReq(req);
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());

        }
    }

    @Override
    public void onOrderTuiSuccess(MsgBean bean) {
        if (orderTuiDialog!=null)
        {
            orderTuiDialog.getEt_content().setText("");
            orderTuiDialog.dismiss();
            HideKeyboard(orderTuiDialog.getEt_content());
        }

        RxToast.success(bean.getMsg());
    }
    public static void HideKeyboard(View v)
    {
        InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
        if ( imm.isActive( ) ) {
            imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 );

        }
    }
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        LoggerUtils.d("支付宝支付成功咯~~~");
                        RxToast.success("支付成功");
                        refreshLayout.autoRefresh();
//                        Bundle bundle = new Bundle();
//                        bundle.putString("money", pay_amount);
//                        bundle.putInt("signPay", signPay);
//                        bundle.putInt("sign", sign);
//                        $startActivityFinish(OrdeFillingPaySuccessActivity.class, bundle);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        LoggerUtils.d("支付宝支付失敗了~~~");
//                        RxToast.error("支付失败!");

                    }
                    break;
                }
                default:
                    break;
            }
        }


    };

    class OrderAdapter extends BaseQuickAdapter<ReleaseListBean.ResultBean.DataBean, BaseViewHolder> {

        int mId;

        public OrderAdapter(int layoutResId, @Nullable List<ReleaseListBean.ResultBean.DataBean> data, int mId) {
            super(layoutResId, data);
            this.mId = mId;
        }

        @Override
        protected void convert(BaseViewHolder helper, final ReleaseListBean.ResultBean.DataBean item) {


            GlideUtil.ImageLoad(this.mContext, item.getIcon(), helper.getView(R.id.icon));
            helper.setText(R.id.title, item.getTitle())
                    .setText(R.id.budget, item.getDeposit())
                    .setText(R.id.created_at, item.getDeposit_time())
            ;
            MyRatingBar ratingbar = helper.getView(R.id.ratingbar);
            ratingbar.setEnabled(false);
            ratingbar.setRating(TextUtils.isEmpty(item.getBus_fraction()) ? 0 : Float.parseFloat(item.getBus_fraction()));
//            .add("已付定金");
//            .add("已接单");
//            .add("待付款");
//            .add("待评价");
//            .add("已完成");
//            .add("已退款");
            helper.addOnClickListener(R.id.tv_btn_colce);
            helper.addOnClickListener(R.id.tv_btn_pay);
            helper.addOnClickListener(R.id.tv_btn_comment);
            helper.addOnClickListener(R.id.tv_btn_tui);
            if (mId == 0) {
                helper.setGone(R.id.tv_btn_colce, true);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (mId == 1) {
                helper.setGone(R.id.tv_btn_colce, true);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (mId == 2) {
                helper.setGone(R.id.tv_btn_colce, true);
                helper.setGone(R.id.tv_btn_pay, true);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (mId == 3) {
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_comment, true);
            } else if (mId == 4) {
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (mId == 5) {
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_comment, false);
                    helper.setGone(R.id.is_tui,true);
                    helper.setText(R.id.is_tui,item.getIs_tui()==1?"申请退款":item.getIs_tui()==2?"退款成功":"退款拒绝");
                if (item.getIs_tui()==3)
                    helper.setGone(R.id.tv_btn_tui,true);
                else helper.setGone(R.id.tv_btn_tui,false);
            }
        }


    }
}



